#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <fcntl.h> 

#define SIZE 256
#define NUM 16
int main()
{
  char cmd[SIZE];
  const char *cmd_line = "[temp@yumoz cmd ]# ";
  while(1){
    cmd[0]=0;
    printf("%s", cmd_line);
    fgets(cmd, SIZE, stdin);
    // printf("%s",cmd);
    cmd[strlen(cmd)-1]='\0';//输入命令的最后一个字符 即 \n 设为\0  

    //重定向
    char *start = cmd;
    while(*start != '\0'){
      if(*start == '>'){
        *start = '\0';
        start++;
        break;
      }
      start++;
    }
    if(*start != '\0'){
      while(isspace(*start)){//
        start++;
      }
      //printf("%s\n", start);
    }
    else{
      start = NULL;
    }
    // 拆分命令/字符串
    char *args[NUM];
    args[0] = strtok(cmd, " ");// 提取第一个空格前的字符串
    int i = 1;
    do {
      args[i] = strtok(NULL, " ");//从第二次开始划分
      if(args[i] == NULL){
        break;
      }
      ++i;
    }while(1);

    pid_t id = fork();
    if(id<0){
      perror("fork error");
      continue;
    }
    else if(id == 0){
      //child
      if(start != NULL){//start ponit a file
        int fd = open(start, O_WRONLY|O_CREAT, 0644);
        if(fd < 0){
          perror("open error");
          exit(2);
        }
        dup2(fd, 1);//重定向到文件
      }
      execvp(args[0], args); //程序替换 不需要带路径 
      exit(11);
    } //child end 

    //parent
    int status = 0;
    pid_t ret = waitpid(id, &status, 0);
    if(ret>0){
       //printf("status code: %d\n", (status>>8));
       printf("eixt code: %d\n", WEXITSTATUS(status));
    }
  }
  return 0;
}
